package org.jwflow.design.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import io.gitee.yaoshanli.engine.FlowEngine;
import io.gitee.yaoshanli.engine.db.JwDbHelper;
import io.gitee.yaoshanli.engine.service.impl.FlowEngineImpl;
import io.gitee.yaoshanli.engine.utils.ConfigUtils;

import javax.sql.DataSource;
import java.util.Properties;

public class JwFlowPlugin {

    private static boolean isStarted = false;
    private static DataSource dataSource;
    private static Properties properties;
    private static FlowEngine engine;

    public JwFlowPlugin() {
    }

    public JwFlowPlugin(DataSource dataSource) {
        this.dataSource=dataSource;
    }

    public boolean start() {
        if (isStarted)
            return true;
        if(dataSource==null)
        {
            Properties prop = ConfigUtils.getProperties();
            //获取数据连接池对象
            try {
                dataSource = DruidDataSourceFactory.createDataSource(prop);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if(dataSource==null)
        {
            throw new RuntimeException("JwFlowPlugin start error: JwFlowPlugin need DataSource");
        }
        JwDbHelper.initialize(dataSource);
        engine=new FlowEngineImpl();
        isStarted = true;
        return true;
    }

    public boolean stop() {
        JwDbHelper.close();
        isStarted = false;
        return true;
    }

    public static FlowEngine getEngine() {
        JwFlowPlugin jwFlowPlugin=new JwFlowPlugin();
        jwFlowPlugin.start();
        return engine;
    }
}
